package v1

import (
	"ginblog/model"
	"ginblog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// 添加文章
func CreateArticle(c *gin.Context) {
	var article model.Article
	_ = c.ShouldBindJSON(&article)

	code := model.CreateArticle(&article)

	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"article": article,
		"message": errmsg.GetErrMsg(code),
	})
}

// 查询所有文章列表
func GetAllArticles(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pagesize"))
	pageNum, _ := strconv.Atoi(c.Query("pagenum"))

	allArticles, code := model.GetAllArticles(pageSize, pageNum)
	c.JSON(http.StatusOK, gin.H{
		"status":      code,
		"allArticles": allArticles,
		"message":     errmsg.GetErrMsg(code),
	})
}

// 查询单个分类下的所有文章
func GetCategoryArticles(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pagesize"))
	pageNum, _ := strconv.Atoi(c.Query("pagenum"))
	id, _ := strconv.Atoi(c.Param("id"))

	categoryArticles, code := model.GetCategoryArticles(id, pageSize, pageNum)
	c.JSON(http.StatusOK, gin.H{
		"status":           code,
		"categoryArticles": categoryArticles,
		"message":          errmsg.GetErrMsg(code),
	})
}

// 查询单个文章信息
func GetArticleInfo(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	article, code := model.GetArticleInfo(id)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"article": article,
		"message": errmsg.GetErrMsg(code),
	})
}

// 编辑文章
func EditArticle(c *gin.Context) {
	var newArticle model.Article
	id, _ := strconv.Atoi(c.Param("id"))
	c.ShouldBindJSON(&newArticle)

	code := model.EditArticle(id, &newArticle)

	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}

// 删除文章
func DeleteArticle(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code := model.DeleteArticle(id)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}
